package com.nfit.service.impl.transaction;

import com.nfit.dao.TransactionMapper;
import com.nfit.entity.Transactions;
import com.nfit.service.TransactionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TransactionServiceImpl implements TransactionsService {
    @Autowired
    private TransactionMapper dao;
    @Autowired
    private StringRedisTemplate template;

    @Override
    public List<Transactions> selectAll(String userEmail) {
        String userId = template.opsForValue().get(userEmail);
        if (userId != null && !userId.equals("")) {
            List<Transactions> transactions = dao.selectAll(userId);
            return transactions;
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public int insert(Transactions transaction) {
        int result = dao.insert(transaction);
        return result;
    }

    @Override
    public Transactions selectTransactionById(String transactionId, String userId) {
        Transactions transaction = dao.selectTransactionById(transactionId, userId);
        return transaction;
    }

    @Override
    public int updateTransaction(Transactions transaction) {
        int result = dao.updateTransaction(transaction);
        return result;
    }

    @Override
    public int deleteTransactionById(String transactionId) {
        int result = dao.deleteTransactionById(transactionId);
        return result;
    }

    @Override
    public double[][] selectAmounts(String userId,String transactionType) {
        int currentYear = LocalDate.now().getYear(); // 获取当前年份

        // 构建日期字符串
        String oldYearStart = String.format("%d-01-01 00:00:00", currentYear - 1);
        String oldYearEnd = String.format("%d-12-31 23:59:59", currentYear-1);
        String currentYearStart = String.format("%d-01-01 00:00:00", currentYear);
        String currentYearEnd = String.format("%d-12-31 23:59:59", currentYear);

        // 查询金额
        Integer oldAmount = dao.selectAmounts(userId,transactionType, oldYearStart, oldYearEnd);
        Integer currentAmount = dao.selectAmounts(userId,transactionType, currentYearStart, currentYearEnd);

        // 构建结果映射
        double[][] amounts = {
                {currentYear - 1, oldAmount},
                {currentYear, currentAmount}
        };
        return amounts;
    }
}
